import React, { PureComponent, Fragment } from 'react';
import { connect } from 'dva';
import { routerRedux } from 'dva/router';
import {
  Card,
  // Button,
  Form,
  // Row,
  // Col,
  // Input,
  Spin,
  Table,
  BackTop,
  // Select,
  // DatePicker,
  notification,
  // Icon,
  // Popover,
  // Affix,
  Divider,
} from 'antd';

import {
  isInvalid,
  formatDatetime,
  formatMoneyToChinese,
  isNumber,
  isMoney,
  searchFromList,
  refitCommonData,
} from '../../../../utils/tools';
// import FooterToolbar from '../../../../components/FooterToolbar';
import DescriptionList from '../../../../components/DescriptionList';
import Ellipsis from '../../../../components/Ellipsis';
import styles from './BasicInfo.less';

// const { TextArea } = Input;
// const FormItem = Form.Item;
const { Description } = DescriptionList;
// const { MonthPicker } = DatePicker;

// const fieldLabels = {
//   title: '商品名称',
//   subtitle: '副标题',
//   origin: '产地',
//   number: '编号',
//   specification: '规格',
//   unit: '单位',
//   buyType: '销售渠道',
//   saleType: '销售类型',
//   rank: '所属类别',
//   shareTitle: '分享标题',
//   shareDescription: '分享描述',
//   image: '图片',
//   stock: '库存',
//   costPrice: '进货价格',
//   salePrice: '销售价格',
//   expressPrice: '配送价格',
//   marketPrice: '市场价格',
//   stockPrice: '服务站价格',
//   pushMoney: '提成',
//   score: '积分',
//   access: '访问量',
//   publishTime: '发布时间',
// };

@connect(({ productOrder, global, loading }) => ({
  productOrder,
  global,
  loading: loading.models.productOrder,
}))
@Form.create()
class BasicInfo extends PureComponent {
  constructor(props) {
    super(props);
    this.state = {
      // width: '100%',
      metaData: {},
      dataLoading: true,
      saving: false,
    };
  }

  componentDidMount() {
    this.isMountedFlag = true;

    const { match } = this.props;
    const { params } = match;
    const { id: productOrderId } = params;

    this.loadData(productOrderId);
  }

  orderStatusList = () => {
    const { global } = this.props;
    return refitCommonData(global.orderStatusList);
  };

  getOrderStatusName = (v, defaultValue = '') => {
    if (isInvalid(v)) {
      return defaultValue;
    }

    const item = searchFromList('flag', v, this.orderStatusList());
    return item == null ? '未知' : item.name;
  };

  payTypeList = () => {
    const { global } = this.props;
    return refitCommonData(global.payTypeList);
  };

  getPayTypeName = (v, defaultValue = '') => {
    if (isInvalid(v)) {
      return defaultValue;
    }

    const item = searchFromList('flag', v, this.payTypeList());
    return item == null ? '未知' : item.name;
  };

  loadData = id => {
    const { dispatch } = this.props;

    this.setState({ dataLoading: true }, () => {
      dispatch({
        type: 'productOrder/get',
        payload: {
          prodictid: id,
        },
      }).then(() => {
        if (this.isMountedFlag) {
          const {
            productOrder: {
              data: { data },
            },
          } = this.props;

          this.setState({ dataLoading: false, metaData: data });
        }
      });
    });
  };

  refitFieldDecoratorOption = (v, justice, defaultValue, originalOption) => {
    const result = originalOption;

    if (justice) {
      result.initialValue = v || (defaultValue || '');
    }

    return result;
  };

  handleSubmit = e => {
    e.preventDefault();
    const {
      dispatch,
      form,
      location: { pathname },
    } = this.props;
    const { metaData } = this.state;
    form.validateFields((err, values) => {
      if (!err) {
        this.setState({ saving: true });
        const submitValue = values;
        submitValue.image = metaData.image;

        dispatch({
          type: 'productOrder/updateBasicInfo',
          payload: submitValue,
        }).then(() => {
          this.setState({ saving: false });
          const {
            productOrder: { data },
          } = this.props;
          const { code, message: messageText } = data;
          if (code === 200) {
            notification.success({
              placement: 'bottomRight',
              message: '操作结果',
              description: '数据已经保存成功，请进行后续操作。',
            });
          } else {
            notification.error({
              placement: 'bottomRight',
              message: '操作结果',
              description: messageText,
            });
          }

          dispatch(
            routerRedux.replace({
              pathname: `${pathname.replace('/load/', '/update/')}`,
            })
          );
        });
      }
    });
  };

  buildFieldDescription = (v, op, other) => {
    const o = (other || '') === '' ? '' : `,${other}`;
    return `请${op || '输入'}${v}${o}!`;
  };

  buyTypeList = () => {
    const { global } = this.props;
    return refitCommonData(global.buyTypeList);
  };

  rankList = () => {
    const { global } = this.props;
    return refitCommonData(global.rankList);
  };

  saleTypeList = () => {
    const { global } = this.props;
    return refitCommonData(global.saleTypeList);
  };

  unitList = () => {
    const { global } = this.props;
    return refitCommonData(global.unitList);
  };

  getUnitName = (v, defaultValue = '') => {
    if (isInvalid(v)) {
      return defaultValue;
    }

    const item = searchFromList('flag', v, this.unitList());
    return item == null ? '未知' : item.name;
  };

  handleFormReset = () => {
    const { dispatch, form } = this.props;
    form.resetFields();
    dispatch({
      type: 'productOrder/getCurrent',
      payload: {},
    }).then(() => {
      const {
        productOrder: { data },
      } = this.props;
      this.setState({ metaData: data });
      this.setState({ saving: false });
    });
  };

  render() {
    const {
      metaData,
      saving,
      //  width,
      dataLoading,
    } = this.state;

    const { list: itemList } = metaData;
    const dataCount = (itemList || []).length;
    let oneData = {};

    if (dataCount === 1) {
      [oneData] = itemList;
    }

    const columns = [
      {
        title: '商品名称',
        dataIndex: 'productName',
        align: 'center',
        render: val => (
          <Fragment>
            <Ellipsis tooltip lines={1}>
              {val || '--'}
            </Ellipsis>
          </Fragment>
        ),
      },
      {
        title: '规格',
        dataIndex: 'chvspec',
        align: 'center',
        render: val => (
          <Fragment>
            <Ellipsis tooltip lines={1}>
              {val || '--'}
            </Ellipsis>
          </Fragment>
        ),
      },
      {
        title: '单位',
        dataIndex: 'intunit',
        align: 'center',
        render: val => (
          <Fragment>
            <Ellipsis tooltip lines={1}>
              {this.getUnitName(val)}
            </Ellipsis>
          </Fragment>
        ),
      },
      {
        title: '单价',
        dataIndex: 'monsaleprice',
        align: 'center',
        render: val => (
          <Fragment>
            <Ellipsis tooltip lines={1}>
              {isMoney(val) ? `￥${val}` : '--'}
            </Ellipsis>
          </Fragment>
        ),
      },
      {
        title: '数量',
        dataIndex: 'count',
        align: 'center',
        render: val => (
          <Fragment>
            <Ellipsis tooltip lines={1}>
              {isNumber(val) ? `${val}` : '--'}
            </Ellipsis>
          </Fragment>
        ),
      },
      {
        title: '积分',
        dataIndex: 'score',
        align: 'center',
        render: val => (
          <Fragment>
            <Ellipsis tooltip lines={1}>
              {isNumber(val) ? `${val}` : '--'}
            </Ellipsis>
          </Fragment>
        ),
      },
      {
        title: '总金额',
        dataIndex: 'totalProductAmount',
        align: 'center',
        render: val => (
          <Fragment>
            <Ellipsis tooltip lines={1}>
              {isMoney(val) ? `￥${val}` : '--'}
            </Ellipsis>
          </Fragment>
        ),
      },
    ];

    return (
      <Fragment>
        <div className={styles.containorBox}>
          <Card
            // title={`订单号：${metaData.serialNumber || ''}`}
            className={styles.card}
            bordered={false}
          >
            <Spin spinning={dataLoading || saving}>
              {dataCount > 0 ? (
                dataCount === 1 ? (
                  <div>
                    <DescriptionList
                      className={styles.headerList}
                      // size="small"
                      col="4"
                    >
                      <Description term="商品名称">{oneData.productName || ''}</Description>
                      <Description term="规格">{oneData.chvspec || ''}</Description>
                      <Description term="单位">{this.getUnitName(oneData.intunit)}</Description>
                      <Description term="单价">
                        {isMoney(oneData.monsaleprice) ? `￥${oneData.monsaleprice}` : ''}
                      </Description>
                      <Description term="数量">
                        {isNumber(oneData.count) ? `${oneData.count}` : ''}
                      </Description>
                      <Description term="积分合计">
                        {isNumber(oneData.score) ? `${oneData.score}` : ''}
                      </Description>
                      <Description term="产品总金额">
                        {isMoney(oneData.totalProductAmount)
                          ? `￥${oneData.totalProductAmount}`
                          : ''}
                      </Description>
                    </DescriptionList>
                    <Divider />
                  </div>
                ) : (
                  <Table columns={columns} dataSource={itemList} pagination={false} />
                )
              ) : null}

              <DescriptionList
                className={dataCount !== 1 ? styles.otherList : null}
                // size="small"
                col="1"
              >
                <Description term="配送费">
                  {isMoney(metaData.monexpressprice) ? `￥${metaData.monexpressprice}` : ''}
                </Description>
                <Description term="备注信息">{metaData.remark || ''}</Description>
                <Description term="合计金额">
                  {isMoney(metaData.amount) ? `￥${metaData.amount}` : ''} (
                  {formatMoneyToChinese(metaData.amount)})
                </Description>
              </DescriptionList>
            </Spin>
          </Card>
          <Card title="支付、税金与退款" className={styles.card} bordered={false}>
            <Spin spinning={dataLoading || saving}>
              <DescriptionList
                className={styles.headerList}
                // size="small"
                col="4"
              >
                <Description term="支付状态">
                  {this.getOrderStatusName(metaData.intstate, '--')}
                </Description>
                <Description term="支付方式">
                  {this.getPayTypeName(metaData.intpaytype, '--')}
                </Description>
                <Description term="发票税金">
                  {isMoney(metaData.taxes) ? `${metaData.taxes}` : ''}元
                </Description>
                <Description term="退款金额">
                  {isMoney(metaData.refund) ? `${metaData.refund}` : ''}元
                </Description>
                <Description term="退款原因">{metaData.refundReason || ''}</Description>
              </DescriptionList>
            </Spin>
          </Card>
          <Card title="消费者信息" className={styles.card} bordered={false}>
            <Spin spinning={dataLoading || saving}>
              <DescriptionList
                className={styles.headerList}
                // size="small"
                col="4"
              >
                <Description term="会员昵称">{metaData.contact || ''}</Description>
                <Description term="账户余额">
                  {isMoney(metaData.purseBalance) ? `${metaData.purseBalance}` : ''}元
                </Description>
                <Description term="账户积分">
                  {isNumber(metaData.purseScore) ? `${metaData.purseScore}` : ''}分
                </Description>
              </DescriptionList>
            </Spin>
          </Card>
          <Card title="审核与配送" className={styles.card} bordered={false}>
            <Spin spinning={dataLoading || saving}>
              <DescriptionList
                className={styles.headerList}
                // size="small"
                col="2"
              >
                <Description term="仓库地址">{metaData.warehouseAddress || ''}</Description>
                <Description term="审核人">{metaData.auditor || ''}</Description>
                <Description term="配送人员">{metaData.deliveryman || ''}</Description>
                <Description term="收货信息">{metaData.address || ''}</Description>
                <Description term="签收人">{metaData.contact || ''}</Description>
                <Description term="签收时间">
                  {formatDatetime(metaData.receiveTime, 'YYYY-MM-DD HH:mm:ss', '--')}
                </Description>
              </DescriptionList>
            </Spin>
          </Card>
        </div>
        <BackTop />
      </Fragment>
    );
  }
}

export default BasicInfo;
